package com.syncomponents.convert;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpHost;
import org.apache.http.client.fluentx.UrlBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sunkey.log.audit.annotation.Audit;
import com.syncomponents.core.MessageConstant;
import com.syncomponents.remoting.IMessage;
import com.syncomponents.remoting.message.HttpMessageRequest;
import com.syncomponents.xml.XmlUtils;

import commonj.sdo.DataObject;

/**
 * 消息转换基类
 * 
 * @author sunkey
 * @date Jan 17, 2014
 */
public abstract class AbstractHttpMessageConvert extends AbstractMessageConvert<DataObject> {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @SuppressWarnings("unchecked")
    @Override
    @Audit(action = "convertReq", message = "{$1}")
    public <T extends IMessage> T convertReq(DataObject dobj, String msg) {
        logger.info("starting to convert request message, action:{}, msgType:{}",
                dobj.getString(MessageConstant.MESSAGE_ACTION), dobj.getString(MessageConstant.MESSAGE_TYPE));
        HttpMessageRequest messageRequest = getMessageRequest(dobj, msg);

        HttpHost httpHost = new HttpHost(getTarget().getHost(), getTarget().getPort());
        messageRequest.setHttpHost(httpHost);

        String paramsStr = dobj.getString(MessageConstant.MESSAGE_PARAMS);
        paramsStr = XmlUtils.unCDATA(paramsStr);
        // 不为空时，把配置的参数和请求的参数组装在一起
        if (StringUtils.isNotBlank(paramsStr)) {
            String url = UrlBuilder.url(messageRequest.getUrl()).queryparam(paramsStr.trim())
                    .queryparam(messageRequest.getParams(), false).build();
            messageRequest.setUrl(url);
        } else {
            String url = UrlBuilder.url(messageRequest.getUrl()).queryparam(messageRequest.getParams(), false).build();
            messageRequest.setUrl(url);
        }
        logger.info("messageRequest url:{}", messageRequest.getUrl());
        return (T) messageRequest;
    }

    @Override
    @Audit(action = "convertResp", message = "{$1}", resourceResolverName = "parameter")
    public Object convertResp(DataObject dobj, Object msg) {
        logger.info("starting to convert response message, action:{}, msgType:{}",
                dobj.getString(MessageConstant.MESSAGE_ACTION), dobj.getString(MessageConstant.MESSAGE_TYPE));
        return getResponse(dobj, msg.toString());
    }

    /**
     * 封装请求实体
     * 
     * @param dobj 消息sdo
     * @param msg 消息文本
     * @return
     */
    public abstract HttpMessageRequest getMessageRequest(DataObject dobj, String msg);

    /**
     * 封装响应消息
     * 
     * @param dobj 消息sdo
     * @param msg 消息文本
     * @return 响应消息
     */
    public abstract Object getResponse(DataObject dobj, String msg);

}
